package com.hnvac.photodemo;

import android.app.DownloadManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.theartofdev.edmodo.cropper.CropImage;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.PublicKey;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static android.app.ProgressDialog.show;

public class MainActivity extends AppCompatActivity {
    public static final String TAG = "MainActivity";

    private Uri imageUri;
    private Uri resultUri;
    private String realFileName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void takephoto(View view) throws IOException {
        //保存拍照之后的结果文件，必须是一个新文件
        File file = new File(getExternalCacheDir(), "image.jpg");
        if (file.exists()) {
            file.delete();
        }
        file.createNewFile();
        //将file转换为Uri
        imageUri = Uri.fromFile(file);

        //2 启动拍照程序
        //创建一个隐式意图，调用拍照程序
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        //指定拍照程序照片存放的文件Uri
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        //是有那个请求码101，启动拍照程序
        startActivityForResult(intent, 101);
    }

    public void cropPhoto(View view) {
        CropImage.activity(imageUri).start(this);
    }

    public void uploadphoto(View view) {

        //创建线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //准备上传的文件对象
                    String s = resultUri.toString();
                    Log.e(TAG, "run:" + s);
                    URI uri = new URI(s);
                    File file = new File(uri);

                    //构建一个MultipartBody
                    //（1）构建Requestbody
                    RequestBody body = RequestBody.create(MediaType.parse("image/png"), file);
                    //（2）构建MultipartBody
                    MultipartBody multipartBody = new MultipartBody.Builder()
                            .setType(MultipartBody.FORM)
                            .addFormDataPart("file", "image.jpg", body)
                            .build();
                    //构建请求Request对象
                    Request request = new Request.Builder()
                            .url("http://10.1.63.232:8080/RestaurantServer/File/doUpload")
                            .post(multipartBody)
                            .build();
                    //执行请求，处理结果
                    OkHttpClient client = new OkHttpClient();
                    Response response = null;

                    response = client.newCall(request).execute();
                    String data = response.body().string();

                    JSONObject jsonObject = new JSONObject(data);
                    realFileName = jsonObject.getString("realFileName");
                    Log.e(TAG, "run:" + data);

                } catch (IOException e) {
                    e.printStackTrace();
                } catch (URISyntaxException e1) {
                    e1.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    public void addFood(View view) throws JSONException {
        EditText etFoodName = (EditText) findViewById(R.id.id_et_food_name);
        EditText etFoodDesc = (EditText) findViewById(R.id.id_et_food_dasc);
        EditText etFoodPrice = (EditText) findViewById(R.id.id_et_food_prisc);

        String foodName = etFoodName.getText().toString();
        String sfoodPrice = etFoodPrice.getText().toString();
        int foodPrice = Integer.parseInt(sfoodPrice);
        String foodDesc = etFoodDesc.getText().toString();
        String foodPic = realFileName;

        JSONObject object = new JSONObject();
        object.put("foodName", foodName);
        object.put("foodPrice", foodPrice);
        object.put("foodDasc", foodDesc);
        object.put("foodPic", foodPic);

        final String jsons = object.toString();

        //完成上传
        new Thread(new Runnable() {
            @Override
            public void run() {

                OkHttpClient client = new OkHttpClient();

                RequestBody body = RequestBody.create(MediaType.parse("application"), jsons);
                String url = "http://10.1.63.232:8080/RestaurantServer/Food/addFood";

                Request request = new Request.Builder()
                        .url(url)
                        .post(body)
                        .build();
                try{
                    Response response = client.newCall(request).execute();
                    String data = response.body().string();
                    Log.e(TAG,"run:"+data);
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }).start();


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 101) {
            //resultCode 表明目标Activity的执行结果状态
            if (resultCode == RESULT_OK) {//拍照
                try {
                    //通过ContentResolver,获得ｕｒｉ对象的字节流
                    InputStream inputStream = getContentResolver().openInputStream(imageUri);
                    //从输入流，构造bitmap
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    //从布局文件中,获取显示图片ImageView
                    ImageView photoInage = (ImageView) findViewById(R.id.id_iv_photo);
                    //bitmap将显示到photoInage中
                    photoInage.setImageBitmap(bitmap);

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            } else if (resultCode == RESULT_CANCELED) {
                Toast.makeText(this, "取消了", Toast.LENGTH_SHORT).show();
            }
        }
        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) //裁切的结果
        {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            resultUri = result.getUri();
            InputStream inputStream = null;
            try {
                inputStream = getContentResolver().openInputStream(resultUri);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            //从输入流，构造bitmap
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            //从布局文件中,获取显示图片ImageView
            ImageView photoInage = (ImageView) findViewById(R.id.id_iv_photo);
            //bitmap将显示到photoInage中
            photoInage.setImageBitmap(bitmap);
        }


    }
}
